package share;

import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.laoxinwen.app.BuildConfig;
import com.laoxinwen.app.R;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.sina.weibo.sdk.openapi.models.ErrorInfo;
import com.sina.weibo.sdk.openapi.models.User;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import common.BaseActivity;
import common.Constants;
import common.UserConfig;
import util.bitmap.FileUtil;
import util.bitmap.Img;

//import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
//import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
//import com.tencent.mm.sdk.modelmsg.WXTextObject;
//import com.tencent.mm.sdk.modelmsg.WXWebpageObject;

/**
 * Created by ilioili on 2015/1/10.
 */
public abstract class ShareActivity extends BaseActivity {
    private static final String TAG_SHARE = "share";
    public static ShareUserInfo userInfo;
    /**
     * 微信开放平台的接口类
     */
    protected static IWXAPI wechat;
    /**
     * QQ和Qzone的分享的接口楼
     */
    protected static Tencent tencent;
    private static AuthInfo sinaAuthInfo;
    private static SsoHandler sinaHandler;
    private static SendAuth.Resp authResp;

    public static void setWechatResult(SendAuth.Resp resp) {
        authResp = resp;
    }

    public void bindQq() {
        tencent.login(this, ShareConstants.QQ_SCOPE, new IUiListener() {
            @Override
            public void onComplete(Object o) {
                com.tencent.connect.UserInfo info = new com.tencent.connect.UserInfo(ShareActivity.this, tencent.getQQToken());
                info.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object o) {
                        try {
                            JSONObject json = (JSONObject) o;
                            if (null != json) {
                                log(o.toString());
                                userInfo.qqToken = tencent.getQQToken().getAccessToken();
                                userInfo.qqOpenId = tencent.getQQToken().getOpenId();
                                userInfo.qqName = json.getString("nickname");
                                userInfo.qqIconUrl = json.getString("figureurl_qq_2");//qq头像100X100
                                UserConfig.updateShareUserInfo(userInfo);
                                onQqInfoObtained();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(UiError uiError) {

                    }

                    @Override
                    public void onCancel() {

                    }
                });
            }

            @Override
            public void onError(UiError uiError) {
            }

            @Override
            public void onCancel() {
                Toast.makeText(ShareActivity.this, "您已取消QQ授权", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void log(String content) {
        if (BuildConfig.DEBUG) {
            Log.i(TAG_SHARE, content);
        }
    }

    protected void onQqInfoObtained() {

    }

    public void bindSina() {
        sinaHandler = new SsoHandler(this, sinaAuthInfo);
        sinaHandler.authorize(new WeiboAuthListener() {
            @Override
            public void onComplete(Bundle values) {
                // 从 Bundle 中解析 Token
                final Oauth2AccessToken mAccessToken = Oauth2AccessToken.parseAccessToken(values);
                if (mAccessToken.isSessionValid()) {
                    // 保存 Token 到 SharedPreferences
                    AccessTokenKeeper.writeAccessToken(ShareActivity.this, mAccessToken);
                    IWeiboShareAPI mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(ShareActivity.this, ShareConstants.SINA_APP_KEY);
                    mWeiboShareAPI.registerApp();

                    UsersAPI mUsersAPI = new UsersAPI(ShareActivity.this, ShareConstants.SINA_APP_KEY, mAccessToken);
                    long uid = Long.parseLong(mAccessToken.getUid());
                    mUsersAPI.show(uid, new RequestListener() {
                        @Override
                        public void onComplete(String response) {
                            if (!TextUtils.isEmpty(response)) {
                                log(response);
                                User user = User.parse(response);
                                userInfo.sinaIconUrl = user.avatar_large;
                                userInfo.sinaName = user.name;
                                userInfo.sinaOpenId = mAccessToken.getUid();
                                userInfo.sinaToken = mAccessToken.getToken();
                                UserConfig.updateShareUserInfo(userInfo);
                                onWeiboInfoObtained();
                            }
                        }

                        @Override
                        public void onWeiboException(WeiboException e) {
                            log(e.getMessage());
                            ErrorInfo info = ErrorInfo.parse(e.getMessage());
                            Toast.makeText(ShareActivity.this, info.toString(), Toast.LENGTH_LONG).show();
                        }
                    });

                } else {
                    // 以下几种情况，您会收到 Code：
                    // 1. 当您未在平台上注册的应用程序的包名与签名时；
                    // 2. 当您注册的应用程序包名与签名不正确时；
                    // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                    String code = values.getString("code");
                    String message = "授权失败";
                    if (!TextUtils.isEmpty(code)) {
                        message = message + "\nObtained the code: " + code;
                    }
                    Toast.makeText(ShareActivity.this, message, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onWeiboException(WeiboException e) {
                Toast.makeText(ShareActivity.this, "新浪授权异常", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancel() {
                Toast.makeText(ShareActivity.this, "取消新浪授权", Toast.LENGTH_LONG).show();
            }
        });

    }

    protected void onWeiboInfoObtained() {

    }

    public void bindWechat() {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "laoxinwen";
        req.transaction = "" + System.currentTimeMillis();
        wechat.sendReq(req);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != authResp) {
            switch (authResp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    try {
                        RequestParams params = new RequestParams();
                        params.put("appid", ShareConstants.WECHAT_APP_ID);
                        params.put("secret", ShareConstants.WECHAT_APP_SECRET);
                        params.put("code", authResp.code);
                        params.put("grant_type", "authorization_code");
                        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
                        final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
                        asyncHttpClient.get(url, params, new TextHttpResponseHandler() {
                            @Override
                            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {

                            }

                            @Override
                            public void onSuccess(int i, Header[] headers, String s) {
                                try {
                                    //                                    jsonObject.getString("refresh_token");
                                    //                                    jsonObject.getInt("expires_in");
                                    JSONObject jsonObject = new JSONObject(s);
                                    userInfo.weixinToken = jsonObject.getString("access_token");
                                    userInfo.weixinOpenId = jsonObject.getString("openid");
                                    RequestParams params = new RequestParams();
                                    params.put("access_token", userInfo.weixinToken);
                                    params.put("openid", userInfo.weixinOpenId);
                                    String url = "https://api.weixin.qq.com/sns/userinfo";
                                    asyncHttpClient.get(url, params, new TextHttpResponseHandler() {
                                        @Override
                                        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {

                                        }

                                        @Override
                                        public void onSuccess(int i, Header[] headers, String s) {
                                            try {
                                                JSONObject json = new JSONObject(s);
                                                userInfo.weixinName = json.getString("nickname");
                                                userInfo.wexinIconUrl = json.getString("headimgurl");
                                                UserConfig.updateShareUserInfo(userInfo);
                                                onWechatInfoObtain();
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    break;
                default:
                    break;
            }
            authResp = null;//一次有效
        }
    }

    protected void onWechatInfoObtain() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userInfo = UserConfig.getShareUserInfo();
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                initQQ();
                initSina();
                initWechat();
            }
        });

    }

    protected void initQQ() {
        try {
            if (null == tencent) {
                tencent = Tencent.createInstance(ShareConstants.QQ_APP_ID, this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Error e) {
            e.printStackTrace();
        }

    }

    protected void initSina() {
        try {
            if (null == sinaAuthInfo) {
                sinaAuthInfo = new AuthInfo(this, ShareConstants.SINA_APP_KEY, ShareConstants.SINA_REDICT_URL, ShareConstants.SINA_SCOPE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Error e) {
            e.printStackTrace();
        }

    }

    protected void initWechat() {
        try {
            if (null == wechat) {
                wechat = WXAPIFactory.createWXAPI(this, ShareConstants.WECHAT_APP_ID, true);
                wechat.registerApp(ShareConstants.WECHAT_APP_ID);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Error e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (null != tencent) {
            tencent.onActivityResult(requestCode, resultCode, data);
        }
        if (null != sinaHandler) {
            sinaHandler.authorizeCallBack(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    protected void unBindQq() {
        if (null == tencent) {
            tencent = Tencent.createInstance(ShareConstants.QQ_APP_ID, this);
        }
        tencent.logout(this);
        userInfo.isQqBinded = false;
        UserConfig.updateShareUserInfo(userInfo);
    }

    protected void unBindSina() {
        //TODO
        userInfo.isSinaBinded = false;
        UserConfig.updateShareUserInfo(userInfo);
    }

    protected void unBindWechat() {
        //TODO
        userInfo.isWexinBinded = false;
        UserConfig.updateShareUserInfo(userInfo);
    }

    protected void shareToQq(String title, String summary, String picUrl, String srcUrl) {

        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, Constants.SHARE_PREFIX + title);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, srcUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, picUrl);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, getResources().getString(R.string.app_name));
        tencent.shareToQQ(this, params, null);
    }

    protected void shareToQqZone(String title, String summary, String picUrl, String srcUrl) {
        //        方式1
        //        final Bundle params = new Bundle();
        //        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        //        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
        //        params.putString(QQShare.SHARE_TO_QQ_TITLE, "[凿音]"+title);
        //        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
        //        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, srcUrl);
        //        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, picUrl);
        //        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, getResources().getString(R.string.app_name));
        //        tencent.shareToQQ(this, params, new IUiListener() {
        //            @Override
        //            public void onComplete(Object o) {
        //            }
        //
        //            @Override
        //            public void onError(UiError uiError) {
        //                showToast(uiError.errorDetail+"\n"+uiError.errorMessage);
        //            }
        //
        //            @Override
        //            public void onCancel() {
        //
        //            }
        //        });


        //        方式2
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, Constants.SHARE_PREFIX + title);//必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);//选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, srcUrl);//必填
        ArrayList<String> list = new ArrayList<>(1);
        list.add(picUrl);
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, list);
        tencent.shareToQzone(this, params, new IUiListener() {
            @Override
            public void onComplete(Object o) {

            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        });
    }

    protected void shareToWeibo(final String title, final String summary, final String picUrl, final String srcUrl) {
        final Img img = new Img(FileUtil.getCacheDir(), FileUtil.getFileDir(), picUrl);
        final ProgressDialog pd = new ProgressDialog(this);
        pd.show();
        img.downloadAndDecodeAsync(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                pd.cancel();
                WebpageObject mediaObject = new WebpageObject();
                mediaObject.identify = Utility.generateGUID();
                mediaObject.title = mediaObject.description = mediaObject.defaultText = " " + summary;
                mediaObject.actionUrl = srcUrl;
                mediaObject.setThumbImage(BitmapFactory.decodeResource(getResources(), R.drawable.icon_share_snap));

                ImageObject imageObject = new ImageObject();
                imageObject.setImageObject(img.getBitmap());

                TextObject textObject = new TextObject();
                textObject.text = Constants.SHARE_PREFIX + title;

                SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
                WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                weiboMessage.imageObject = imageObject;
                weiboMessage.mediaObject = mediaObject;
                weiboMessage.textObject = textObject;
                // 用transaction唯一标识一个请求
                request.transaction = String.valueOf(System.currentTimeMillis());
                request.multiMessage = weiboMessage;
                request.packageName = getPackageName();
                // 3. 发送请求消息到微博，唤起微博分享界面
                IWeiboShareAPI mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(ShareActivity.this, ShareConstants.SINA_APP_KEY);

                // 注册第三方应用到微博客户端中，注册成功后该应用将显示在微博的应用列表中。
                // 但该附件栏集成分享权限需要合作申请，详情请查看 Demo 提示
                // NOTE：请务必提前注册，即界面初始化的时候或是应用程序初始化时，进行注册
                boolean b = mWeiboShareAPI.registerApp();
                mWeiboShareAPI.sendRequest(ShareActivity.this, request);

                //                Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
                //                String token = "";
                //                if (accessToken != null) {
                //                    token = accessToken.getToken();
                //                }
                //
                //                mWeiboShareAPI.sendRequest(ShareActivity.this, request, sinaAuthInfo, token, new WeiboAuthListener() {
                //
                //                    @Override
                //                    public void onWeiboException(WeiboException arg0) {
                //                        System.out.print("xxx" + arg0);
                //                    }
                //
                //                    @Override
                //                    public void onComplete(Bundle bundle) {
                //                        // TODO Auto-generated method stub
                //                        Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
                //                        AccessTokenKeeper.writeAccessToken(ShareActivity.this, newToken);
                //                        Toast.makeText(ShareActivity.this, "分享成功" + newToken.getToken(), Toast.LENGTH_SHORT).show();
                //                    }
                //
                //                    @Override
                //                    public void onCancel() {
                //                    }
                //                });
            }
        });


    }

    protected void shareToWeixin(final String title, final String summary, String picUrl, final String srcUrl) {
        final Img img = new Img(FileUtil.getCacheDir(), FileUtil.getFileDir(), picUrl);
        img.setSize(100, 100);
        final ProgressDialog pd = new ProgressDialog(this);
        pd.show();
        img.downloadAndDecodeAsync(new Handler() {
            @Override
            public void handleMessage(Message m) {
                pd.cancel();
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = srcUrl;
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = Constants.SHARE_PREFIX + title;
                msg.description = summary;
                Bitmap thumb = img.getBitmap() == null ? BitmapFactory.decodeResource(getResources(), R.drawable.icon_share_snap) : img.getBitmap();
                msg.thumbData = bmpToByteArray(thumb, true);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession;
                wechat.sendReq(req);
            }
        });
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    protected void shareToWeixinFriendCircle(final String title, final String summary, String picUrl, final String srcUrl) {
        final Img img = new Img(FileUtil.getCacheDir(), FileUtil.getFileDir(), picUrl);
        img.setSize(100, 100);
        final ProgressDialog pd = new ProgressDialog(this);
        pd.show();
        img.downloadAndDecodeAsync(new Handler() {
            @Override
            public void handleMessage(Message m) {
                pd.cancel();
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = srcUrl;
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = Constants.SHARE_PREFIX + title;
                msg.description = summary;
                Bitmap thumb = img.getBitmap() == null ? BitmapFactory.decodeResource(getResources(), R.drawable.icon_share_snap) : img.getBitmap();
                msg.thumbData = bmpToByteArray(thumb, true);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                wechat.sendReq(req);
            }
        });
    }

    protected void shareCopyUrl(final String srcUrl) {
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setPrimaryClip(ClipData.newPlainText(null, srcUrl));
        showToast("已复制到系统剪切板");
    }
}
